package com.pingpang.websocketchat;

import java.io.File;
import java.net.URL;
import java.util.concurrent.TimeUnit;

import javax.net.ssl.SSLContext;
import javax.net.ssl.SSLEngine;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.pingpang.util.SslUtil;

import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelPipeline;
import io.netty.channel.socket.SocketChannel;
import io.netty.handler.codec.http.HttpObjectAggregator;
import io.netty.handler.codec.http.HttpServerCodec;
import io.netty.handler.codec.http.websocketx.WebSocketServerProtocolHandler;
import io.netty.handler.ssl.SslHandler;
import io.netty.handler.stream.ChunkedWriteHandler;
import io.netty.handler.timeout.IdleStateHandler;

/**
 * 服务端 ChannelInitializer
 */
public class WebsocketChatServerInitializer extends ChannelInitializer<SocketChannel> {
	
	//日志操作
    private Logger logger = LoggerFactory.getLogger(WebsocketChatServerInitializer.class);
	
	@Override
    public void initChannel(SocketChannel ch) throws Exception {
		ChannelPipeline pipeline = ch.pipeline();
		 
        pipeline.addLast(new IdleStateHandler(10,0, 0, TimeUnit.SECONDS));
         
        pipeline.addLast(new HttpServerCodec());
		pipeline.addLast(new HttpObjectAggregator(64*1024));
		pipeline.addLast(new ChunkedWriteHandler());
		//pipeline.addLast(new HttpRequestHandler("/ws"));
		pipeline.addLast(new WebSocketServerProtocolHandler("/ws"));
		//pipeline.addLast(new HeartbeatServerHandler());
		pipeline.addLast(new TextWebSocketFrameHandler());

		logger.info(WebsocketChatServerInitializer.class.getResource("/").toString());
		
		 URL xmlpath = this.getClass().getClassLoader().getResource("");
         logger.info(xmlpath.toString());
         //File f = new File(this.getClass().getResource("/").getPath());
         File f = new File(WebsocketChatServerInitializer.class.getResource("").toString());
         logger.info(f.getAbsolutePath());
		
         SSLContext sslContext = SslUtil.createSSLContext("PKCS12",this.getClass().getClassLoader().getResourceAsStream("keystore.p12"),"changeit");
		 //SSLEngine engine = sslContext.createSSLEngine(); 
		 SSLEngine sslEngine = sslContext.createSSLEngine();
         sslEngine.setNeedClientAuth(false);
         sslEngine.setUseClientMode(false);
         pipeline.addFirst(new SslHandler(sslEngine));
    }
}
